package org.breathe.dynamic.thread.pool.core.handler;

import lombok.extern.slf4j.Slf4j;
import org.breathe.dynamic.thread.pool.core.context.BreatheDtpContextHolder;
import org.breathe.dynamic.thread.pool.core.notify.Notifier;
import org.breathe.thread.pool.common.entity.BreatheDtpMainProperties;
import org.breathe.thread.pool.common.entity.NotifyItem;
import org.breathe.thread.pool.common.enums.NotifyTypeEnum;

import java.util.*;

/**
 * 通知处理器
 * @author: breathe
 * @createTime: 2025-04-13
 */
@Slf4j
public class NotifierHandler {

    /**
     * 存放通知
     * key为平台名，value为需要发的通知
     */
    private static final Map<String, Notifier> NOTIFIERS = new HashMap<>();

    /**
     * 构造方法
     */
    private NotifierHandler() {
        //通过spi机制来实现实现类的添加
        ServiceLoader.load(Notifier.class).forEach(each -> NOTIFIERS.put(each.platform().toLowerCase(), each));
        log.info("NOTIFIERS: {}", NOTIFIERS);
    }

    /**
     * 发送通知
     * @param properties 动态线程池配置
     * @param diffs 不同
     */
    public void sendNotice(BreatheDtpMainProperties properties, List<String> diffs) {
        try {
            //通知实体
            NotifyItem notifyItem = BreatheDtpContextHolder.get().getNotifyItem();
            //遍历所有需要发送通知的平台
            for (String platform : new HashSet<>(notifyItem.getPlatforms())) {
                Notifier notifier = NOTIFIERS.get(platform.toLowerCase());
                //发送通知
                if (notifier != null) {
                    notifier.sendChangeMsg(properties, diffs);
                }
            }
        } finally {
            BreatheDtpContextHolder.remove();
        }
    }

    /**
     * 发送报警
     * @param typeEnum 通知类型 ，参考枚举类
     */
    public void sendAlarm(NotifyTypeEnum typeEnum) {
        try {
            //获取通知实体
            NotifyItem notifyItem = BreatheDtpContextHolder.get().getNotifyItem();
            //遍历平台
            for (String platform : notifyItem.getPlatforms()) {
                //获取通知并发送
                Notifier notifier = NOTIFIERS.get(platform.toLowerCase());
                if (notifier != null) {
                    notifier.sendAlarmMsg(typeEnum);
                }
            }
        } finally {
            BreatheDtpContextHolder.remove();
        }
    }

    /**
     * 获取instance
     * @return
     */
    public static NotifierHandler getInstance() {
        return NotifierHandlerHolder.INSTANCE;
    }

    /**
     * 懒得再开一个类了，直接写这吧
     */
    public static class NotifierHandlerHolder {
        private static final NotifierHandler INSTANCE = new NotifierHandler();
    }
}
